﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web.Mvc;
using Xenta.Attributes;
using Xenta.Structs;
using Xenta.Utils;

namespace Xenta.Web.Controllers
{
    public sealed class MediaController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index()
        {
            dynamic m = new ExpandoObject();
            m.Folders = Svc.ProcessOperation("SearchFileFolders", new
            {
                LanguageID = JDM.Int32(Svc.Localization.Language.EntityID),
                FlagMask = "Active,Public"
            }, new
            {
                DisclosureLevel = "Base"
            });
            m.Files = Svc.ProcessOperation("SearchFiles", new
            {
                FlagMask = "Active,Public"
            }, new
            {
                DisclosureLevel = "Base"
            }); 
            return View(m);
        }

        [HttpGet, ActionCache("medium", VaryByParam = "guid;size")]
        public ActionResult Image(Guid guid, int? size)
        {
            var m = Svc.ProcessOperation("GetFileByGuid", new
            {
                Guid = guid
            }, new
            {
                DisclosureLevel = "Base"
            });
            if(m == null)
                return HttpNotFound();
            Guid fileGuid = JDM.Guid(m.Guid);
            string fileName = JDM.String(m.Name);
            string fileType = JDM.String(m.MimeType);
            fileName = String.Format("{0}-{1}", fileGuid, fileName);
            var fileTForm = new List<TransformInfo>();
            if(size.HasValue)
            {
                size = Math.Max(size.Value, Svc.Config(Par.In("WebPortal").Of(this)
                        .Group("Image").Name("MinSize"), 8));
                size = Math.Min(size.Value, Svc.Config(Par.In("WebPortal").Of(this)
                    .Group("Image").Name("MaxSize"), 1024));
                fileName = String.Format("{0}-{1}", size, fileName);
                fileTForm.Add(new TransformInfo
                {
                    ID = Guid.Parse("d15452ad-1e6f-492a-b2e2-dbce11bcb4ec"),
                    Properties = new Dictionary<String, String>
                    {
                        {"Size", size.Value.ToString()}
                    }
                });
            }
            if(Svc.Config<Boolean>(Par.In("WebPortal").Of(this)
                .Group("Watermark")
                .Name("Enabled")))
            {
                fileTForm.Add(new TransformInfo
                {
                    ID = Guid.Parse("f6f3b677-d9b5-4873-a164-47d535a49337"),
                    Properties = new Dictionary<String, String>
                    {
                        {"Text", Svc.Config(Par.In("WebPortal").Of(this)
                            .Group("Watermark")
                            .Name("Text"))},
                        {"Position", Svc.Config(Par.In("WebPortal").Of(this)
                            .Group("Watermark")
                            .Name("Position"))},
                        {"Padding", Svc.Config(Par.In("WebPortal").Of(this)
                            .Group("Watermark")
                            .Name("Padding"))},
                        {"BgClrArgb", Svc.Config(Par.In("WebPortal").Of(this)
                            .Group("Watermark")
                            .Name("BgClrArgb"))},
                        {"FgClrArgb", Svc.Config(Par.In("WebPortal").Of(this)
                            .Group("Watermark")
                            .Name("FgClrArgb"))},
                        {"FontFamily", Svc.Config(Par.In("WebPortal").Of(this)
                            .Group("Watermark")
                            .Name("FontFamily"))},
                        {"FontSize", Svc.Config(Par.In("WebPortal").Of(this)
                            .Group("Watermark")
                            .Name("FontSize"))},
                    }
                });
            }
            string imgType = String.Empty;
            var imgStream = Svc.DownloadFile(fileGuid, 
                out imgType,
                fileTForm);
            if(fileType != imgType)
                fileName = String.Format("{0}.{1}", fileName, MimeTypeHelper.TypeToExt(imgType));
            return File(imgStream, imgType, fileName);
        }

        [HttpGet, ActionCache("long", VaryByParam = "guid")]
        public ActionResult Download(Guid guid)
        {
            var m = Svc.ProcessOperation("GetFileByGuid", new
            {
                Guid = guid
            }, new
            {
                DisclosureLevel = "Base"
            });
            if(m == null)
                return HttpNotFound();

            Guid fileGuid = JDM.Guid(m.Guid);
            string fileType = JDM.String(m.MimeType);
            string fileName = JDM.String(m.Name);
            fileName = String.Format("{0}-{1}", fileGuid, fileName);
            string dwlType = String.Empty;
            var dwlStream = Svc.DownloadFile(fileGuid, out dwlType);
            if(dwlType != fileType)
                fileName = String.Format("{0}.{1}", fileName, MimeTypeHelper.TypeToExt(dwlType));
            return File(dwlStream, dwlType, fileName);
        }

        #endregion

        #region Child Actions

        [ChildActionOnly]
        public ActionResult _DefaultImage(int groupID, int? size)
        {
            dynamic m = new ExpandoObject();

            m.Size = size;
            m.File = (Svc.ProcessOperation("SearchFiles", new
            {
                GroupID = groupID,
                MimeType = new
                {
                    Expression = "image%"
                },
                SortBy = new[] 
                {
                    "Name"
                },
                Count = 1
            }, new
            {
                DisclosureLevel = "Base"
            }).Items as IEnumerable<dynamic>)
                .FirstOrDefault();
            return PartialView("_Image", m);
        }

        [ChildActionOnly]
        public ActionResult _Attachments(int groupID)
        {
            var m = Svc.ProcessOperation("SearchFiles", new
            {
                GroupID = groupID,
                SortBy = new[] 
                {
                    "Name"
                }
            }, new
            {
                DisclosureLevel = "Base"
            }).Items;
            return PartialView(m);
        }

        #endregion
    }
}
